import * as mars3d from "mars3d"
import { Cesium } from "mars3d"
import { ref } from "vue"
import { useApiStore } from "../../pages/jcxm/stores/user"
import axios from "axios"
import {Local, MoveInOne} from "@icon-park/svg";
import {$alert as globalAlert} from "@mars/components/mars-ui";
export let map: any // mars3d.Map三维地图对象
export const eventTarget: mars3d.BaseClass = new mars3d.BaseClass()

/**
 * 初始化地图业务，生命周期钩子函数（必须）
 * 框架在地图初始化完成后自动调用该函数
 * @param {mars3d.Map} mapInstance 地图对象
 * @returns {void} 无
 */
export function onMounted(mapInstance: any): void {
  map = mapInstance // 记录map
  console.log(map)
  const underground = new mars3d.thing.Underground({
    alpha: 0.5,
    enabled: true,
    id: "underground"
  })
  map.addThing(underground)
  bindMapContextMenu(map)
  loadpipelinegeojson("http://82.157.98.251:6789/RainPipe/YS_LINE.json", "雨水管道", { color: "#71eef4", speed: 10, percent: 0.15, alpha: 1 })
  loadpipelinegeojson("http://82.157.98.251:6789/RainPipe/WS_LINE.json", "污水管道", { color: "#d52fe0", speed: 10, percent: 0.15, alpha: 1 })
  loadpipelinegeojson("http://82.157.98.251:6789/RainPipe/HS_LINE.json", "合流管道", { color: "#de8938", speed: 10, percent: 0.15, alpha: 1 })
  loadpipepointgeojson("http://82.157.98.251:6789/RainPipe/YS_POINT.json","雨水井")
  loadpipepointgeojson("http://82.157.98.251:6789/RainPipe/WS_POINT.json","污水井")
  loadpipepointgeojson("http://82.157.98.251:6789/RainPipe/HS_POINT.json","合流井")
}

/**
 * 释放当前地图业务的生命周期函数
 * @returns {void} 无
 */
export function onUnmounted() {
  map = null
}

export function loadpipelinegeojson(url, id, materialOptions = {}) {
  const geojsonLayer1 = new mars3d.layer.GeoJsonLayer({
    name: id,
    // url: "http://82.157.98.251:6789/model_gltf/" + url,
    url: url,
    id: id,
    show: true,
    symbol: {
      type: "polylineVolume",
      styleOptions: {
        shape: "circle",
        radius: "{管径断面}",
        // setHeight:25,
        // addHeight:10,
        cornerType: Cesium.CornerType.BEVELED,
        materialType: mars3d.MaterialType.LineFlowColor,
        materialOptions: materialOptions
      },
      callback: function (attr, styleOpt) {
        // 从 attr 中获取 "管径断面" 属性，并将其转换为半径（单位：米）
        let diameter = parseFloat(attr["管径断面"]) / 1000
        let radius = diameter/2
        // 添加容错机制：当计算结果无效时使用默认值0.3
        if (isNaN(radius) || radius <= 0) {
          radius = 0.3 // 设置默认半径值
        }
        const startHeight = parseFloat(attr["起始点高程"]) - radius * 2 - 0.7
        const endHeight = parseFloat(attr["终止点高程"]) - radius * 2 - 0.7
        const setHeight = [startHeight, endHeight]
        // let groundElevation = parseFloat(attr["起始高程"]);
        // let addHeight = isNaN(groundElevation) ? 30 : groundElevation - 25 - radius*2;
        // 返回一个包含样式字段的对象

        return {
          radius: radius, // 设置半径（带容错机制）
          setHeight:setHeight,
          // addHeight: addHeight, // 新增计算的高度差
          color: styleOpt.color, // 继承默认颜色
          opacity: styleOpt.opacity // 继承默认透明度
        }
      }
    },
    flyTo: true,
    popup: [
      { field: "管线材料", name: "管线材料" },
      { field: "管径断面", name: "管径断面" },
      { field: "物探点号", name: "物探点号" },
      { field: "起始点X座标", name: "起始点X座标" },
      { field: "起始点Y座标", name: "起始点Y座标" },
      { field: "起始点高程", name: "起始点高程" },
      { field: "起始点埋深", name: "起始点埋深" },
      { field: "连接方向", name: "连接方向" },
      { field: "终止点X座标", name: "终止点X座标" },
      { field: "终止点Y座标", name: "终止点Y座标" },
      { field: "终止点高程", name: "终止点高程" },
      { field: "终止点埋深", name: "终止点埋深" },
    ],
  })
  bindLayerContextMenu(geojsonLayer1,'line')
  map.addLayer(geojsonLayer1)
}

export function loadpipepointgeojson(url, id, color = "#ffffff") {
  const geojsonLayer = new mars3d.layer.GeoJsonLayer({
    name: id,
    // url: "//82.157.98.251:6789/RainPipe/" + url,
    url: url,
    id: id,
    show: true,
    symbol: {
      type: "circle",
      styleOptions: {
        diffHeight: "{起始点埋深}",
        radius: 1,
        color: color,
        scale: 1.0, // 统一缩放比例
        // addHeight:10,
        // color: color
      },
      callback: function (attr, styleOpt) {
        // 从 attr 中获取 "管径断面" 属性，并将其转换为半径（单位：米）
        let diffHeight = parseFloat(attr["起始点埋深"])

        // 添加容错机制：当计算结果无效时使用默认值0.6
        if (isNaN(diffHeight) || diffHeight <= 0) {
          diffHeight = 1 // 设置默认井深
        }
        let groundElevation = parseFloat(attr["地面高程"]);
        let height = isNaN(groundElevation) ? 30 : groundElevation - diffHeight;

        // 返回一个包含样式字段的对象
        return {
          diffHeight: diffHeight, // 设置半径（带容错机制）
          height: height, // 新增计算的高度差
          color: styleOpt.color, // 继承默认颜色
          opacity: styleOpt.opacity // 继承默认透明度
        }
      }
    },
    popup: [
      { field: "物探点号", name: "物探点号" },
      { field: "特征", name: "特征" },
      { field: "附属物", name: "附属物" },
      { field: "X座标", name: "X座标" },
      { field: "Y座标", name: "Y座标" },
      { field: "高程", name: "管底高程" },
      { field: "埋深", name: "起始点埋深" },
      { field: "管线材料", name: "管线材料" }
    ]
  })
  bindLayerContextMenu(geojsonLayer,'point')
  map.addLayer(geojsonLayer)
}

function bindLayerContextMenu(geojsonLayer,type:string) {
  geojsonLayer.bindContextMenu([
    // {
    //   text: (e)=>{
    //     const graphic = e.graphic
    //     console.log("打印Graphic")
    //     console.log(e)
    //     return "123123"
    //   },
    //   icon: Local({ theme: "outline", fill: "#fff", size: "18" }),
    //   show: function (e) {
    //     return Cesium.defined(e.cartesian)
    //   }
    // },
    {
      text: "查看此处坐标",
      icon: Local({ theme: "outline", fill: "#fff", size: "18" }),
      show: function (e) {
        return Cesium.defined(e.cartesian)
      },
      callback: function (e) {
        // 经纬度
        const mpt = mars3d.LngLatPoint.fromCartesian(e.cartesian)
        const ptNew = mars3d.PointTrans.proj4Trans([mpt.lng, mpt.lat], "EPSG:4326", mars3d.CRS.CGCS2000_GK_Zone_3)
        console.log("proj4Trans", ptNew)
        const inhtml = `
         经度:${mpt.lng}, 纬度:${mpt.lat}, 海拔:${mpt.alt},

         横坐标:${ptNew[0].toFixed(1)}, 纵坐标:${ptNew[1].toFixed(1)} (CGCS2000)
        `
        globalAlert(inhtml, "位置信息")
      }
    },
    {
      text: "移动到此处",
      icon: MoveInOne({ theme: "outline", fill: "#fff", size: "18" }),
      show: function (e) {
        return Cesium.defined(e.cartesian)
      },
      callback: function (e) {
        const cameraDistance = Cesium.Cartesian3.distance(e.cartesian, map.camera.positionWC) * 0.1

        map.flyToPoint(e.cartesian, {
          radius: cameraDistance, // 距离目标点的距离
          maximumHeight: map.camera.positionCartographic.height
        })
      }
    },
    {
      text: "删除对象",
      icon: "fa fa-trash-o",
      show: (event) => {
        const graphic = event.graphic
        if (!graphic || graphic.isDestroy) {
          return false
        } else {
          return true
        }
      },
      callback: (e) => {
        const graphic = e.graphic
        if (!graphic) {
          return
        }
        const parent = graphic.parent // 右击是编辑点时
        geojsonLayer.removeGraphic(graphic)
        if (parent) {
          geojsonLayer.removeGraphic(parent)
        }
        // eventTarget.fire("removeMarker", { id: graphic.id })
      }
    },
    {
      text: "修改属性",
      icon: "fa fa-edit",
      show: (event) => {
        const graphic = event.graphic
        if (!graphic || graphic.isDestroy) {
          return false
        } else {
          return true
        }
      },
      callback: (e) => {
        const graphic = e.graphic
        console.log("查看对象", graphic)
        if (!graphic) {
          return
        }
        const attr = graphic.attr
        const inhtml = `
          <div>
            <div>物探点号:${attr["物探点号"]}</div>
            <div>X座标:${attr["X座标"]}</div>
            <div>Y座标:${attr["Y座标"]}</div>
          </div>
          `
        eventTarget.fire("modification",{graphic:graphic, attr:attr,dataType:type})
      }
    }
  ])
}

function bindMapContextMenu(map) {
  map.bindContextMenu([
    {
      text: "查看此处坐标",
      icon: Local({ theme: "outline", fill: "#fff", size: "18" }),
      show: function (e) {
        return Cesium.defined(e.cartesian)
      },
      callback: function (e) {
        // 经纬度
        const mpt = mars3d.LngLatPoint.fromCartesian(e.cartesian)
        const ptNew = mars3d.PointTrans.proj4Trans([mpt.lng, mpt.lat], "EPSG:4326", mars3d.CRS.CGCS2000_GK_Zone_3)
        console.log("proj4Trans", ptNew)
        const inhtml = `
         经度:${mpt.lng}, 纬度:${mpt.lat}, 海拔:${mpt.alt},

         横坐标:${ptNew[0].toFixed(1)}, 纵坐标:${ptNew[1].toFixed(1)} (CGCS2000)
        `
        globalAlert(inhtml, "位置信息")
      }
    },
    {
      text: "移动到此处",
      icon: MoveInOne({ theme: "outline", fill: "#fff", size: "18" }),
      show: function (e) {
        return Cesium.defined(e.cartesian)
      },
      callback: function (e) {
        const cameraDistance = Cesium.Cartesian3.distance(e.cartesian, map.camera.positionWC) * 0.1

        map.flyToPoint(e.cartesian, {
          radius: cameraDistance, // 距离目标点的距离
          maximumHeight: map.camera.positionCartographic.height
        })
      }
    },
    {
      text: "添加井点",
      icon: "fa fa-plus",
      show: function (e) {
        return Cesium.defined(e.cartesian)
      },
      callback: function (e) {
        const cartesian = e
        console.log("添加井点坐标数据", cartesian)
        eventTarget.fire("CreateGraphic",{coordinate:cartesian,dataType:"point"})
      }
    },
    {
      text: "添加管线",
      icon: "fa fa-plus",
      show: function (e) {
        return Cesium.defined(e.cartesian)
      },
      callback: function (e) {
        const cartesian = e
        eventTarget.fire("CreateGraphic",{coordinate:cartesian,dataType:"line"})
      }
    }
  ])
}
